<script setup lang="tsx">
import { computed, reactive, ref } from 'vue';
import type { Ref } from 'vue';
import { TableDataWithIndex, useBoolean } from '@sa/hooks';
import { fetchGetAllPages, fetchGetMenuList } from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { yesOrNoRecord } from '@/constants/common';
import { enableStatusRecord, menuTypeRecord } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import ConfigOperateModal, { type OperateType } from './modules/config-operate-modal.vue';
import { ApiMenuItem, ApiMenuQuery, ApiMenuRouteOut, ApimenuserviceApi, ApiSysDataConfigOut, ApiSysDataConfigQuery, PgType } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import { title } from 'process';
import { SysdataconfigApi } from '@/api-services/apis/sysdataconfig-api';
import { Tag } from '@visactor/vue-vtable';
//import Button from 'element-plus/es/components/button';
//import Popconfirm from 'element-plus/es/components/popconfirm';
import { ElButton, ElPopconfirm, ElTag, formatter } from 'element-plus';

const { bool: visible, setTrue: openModal } = useBoolean();
const { tableWrapperRef, scrollConfig } = useTableScroll();

// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const tableLoading = ref(false);
const tableData = reactive<ApiSysDataConfigOut[]>([])
const tableQuery = reactive<ApiSysDataConfigQuery>({
  keyWords: ''
});
const column: UI.TableColumn<ApiSysDataConfigOut>[] = [
  {
    label: 'id',
    //dataIndex: 'id',
    prop: 'id',
    minWidth: 150,
    // align:'center'
  },
  {
    //名称
    label: $t('page.manage.sysConfig.name'),
    //dataIndex: 'name',
    prop: 'name',
    minWidth: 200
  },
  {
    label: 'Key',
    //dataIndex: 'key',
    prop: 'key',
    minWidth: 200
  },
  {
    //数值
    label: $t('page.manage.sysConfig.value'),
    //dataIndex: 'value',
    prop: 'value',
    minWidth: 200
  },
  {
    //数值拓展
    label: $t('page.manage.sysConfig.valueEx'),
    //dataIndex: 'valueEx',
    prop: 'valueEx',
    minWidth: 120
  },

  {
    //分组名称
    label: $t('page.manage.sysConfig.groupName'),
    //dataIndex: 'groupName',
    prop: 'groupName',
    minWidth: 200
  },
  {
    prop: 'isEnable',
    label: $t('page.manage.menu.menuStatus'),
    align: 'center',
    minWidth: 80,
    formatter: record => {
      if (record.isEnable === null) {
        return '';
      }
      const label = $t(record.isEnable ? 'page.manage.common.status.enable' : 'page.manage.common.status.disable');
      const color = record.isEnable ? 'success' : 'warning'

      return <ElTag color={color}> {label} </ElTag>;
    }
  },
  {
    //顺序
    label: $t('page.manage.sysConfig.sort'),
    //dataIndex: 'sort',
    prop: 'sort',
    minWidth: 60,
    align: 'center',
  },
  {
    //备注
    label: $t('page.manage.common.remark'),
    //dataIndex: 'remark',
    prop: 'remark',
  },
  {
    prop: 'operate',
    label: $t('common.operate'),
    minWidth: 270,
    align: 'center',
    fixed: 'right',
    formatter: record => (
      <div class="flex-center" >
        {
          record.pId == 0 && (
            <ElButton type="primary" plain size="small" onClick={() => handleAddChildMenu(record)}>
              {$t('page.manage.menu.addChildMenu')}
            </ElButton>
          )}
        <ElButton type="primary" plain size="small" onClick={() => handleEdit(record)}>
          {$t('common.edit')}
        </ElButton>
        <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id!)}>
          {{
            reference: () => (
              <ElButton type="danger" plain size="small">
                {$t('common.delete')}
              </ElButton>
            )
          }}
        </ElPopconfirm>

      </div>
    )
  }
];
const queryData = async () => {
  tableLoading.value = true;
  const [err, res] = await feature(getAPI(SysdataconfigApi).getTreeList(tableQuery));
  tableLoading.value = false;
  queryDone(err, () => {
    if (res?.data.data) {
      //清空tabledata的数据
      tableData.splice(0);
      tableData.push(...res.data.data);
    } else {
      window.$message?.error($t('common.failed'));
    }
    console.log(tableData)
  })
};


const operateType = ref<OperateType>('add');

function handleAdd() {
  operateType.value = 'add';
  openModal();
}

async function handleBatchDelete(ids: string) {
  // request
  const [err, res] = await feature(getAPI(ApimenuserviceApi)._delete(ids));
  queryDone(err, () => {
    if (res?.data.data) {
      window.$message?.success($t('common.success'));
      queryData();
    } else {
      window.$message?.error($t('common.failed'));
    }
  })
}

async function handleDelete(id: number | string) {
  // request
  handleBatchDelete(id.toString())
}
/** the edit menu data or the parent menu data when adding a child menu */
const editingData: Ref<ApiSysDataConfigOut | null> = ref(null);

function handleEdit(item: ApiSysDataConfigOut) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}

function handleAddChildMenu(item: ApiSysDataConfigOut) {
  operateType.value = 'addChild';

  editingData.value = { ...item };

  openModal();
}



function init() {
  queryData();
}

// init
init();
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.manage.sysConfig.title') }}</p>
          <ElSpace>

            <ElButton size="small" plain type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="align-sub text-icon" />
              </template>
              <span class="ml-8px">{{ $t('common.add') }}</span>
            </ElButton>
            <ElButton size="small" @click="queryData">
              <template #icon>
                <icon-mdi-refresh class="align-sub text-icon" :class="{ 'animate-spin': tableLoading }" />
              </template>
              <span class="ml-8px">{{ $t('common.refresh') }}</span>
            </ElButton>
          </ElSpace>
        </div>

      </template>
      <ElTable height="100%" border class="sm:h-full" :data="tableData" row-key="id">
        <ElTableColumn v-for="col in column" :key="col.prop" v-bind="col" />
      </ElTable>
    </ElCard>
    <ConfigOperateModal v-model:visible="visible" :operate-type="operateType" :row-data="editingData"
      @submitted="queryData" />

  </div>
</template>

<style scoped></style>
